FROM python:3.9-slim

# Set working directory
WORKDIR /app

# Install system dependencies including GDAL and Java
RUN sed -i 's|http://deb.debian.org|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources && \
    apt-get update && apt-get install -y \
    gcc \
    g++ \
    libgdal-dev \
    gdal-bin \
    default-jdk \
    default-jre \
    && rm -rf /var/lib/apt/lists/*

# Set GDAL environment variables
ENV CPLUS_INCLUDE_PATH=/usr/include/gdal
ENV C_INCLUDE_PATH=/usr/include/gdal

# Upgrade pip first
RUN pip install --upgrade pip

# Install all Python dependencies with compatible versions
COPY requirements.txt .
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple \
    pyspark>=3.4.0 \
    fastapi>=0.104.0 \
    uvicorn[standard]>=0.24.0 \
    pydantic>=2.5.0 \
    numpy>=1.24.0 \
    pandas>=2.0.0 \
    scikit-learn>=1.3.0 \
    scipy>=1.11.0

RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple \
    annoy>=1.17.3 \
    faiss-cpu>=1.7.4

# Install geospatial packages with specific versions to avoid GDAL conflicts
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple \
    GDAL==3.7.3 \
    geopandas==0.14.1 \
    shapely==2.0.2 \
    fiona==1.9.4 \
    pyogrio==0.7.2 \
    pyproj==3.6.1 \
    rasterio==1.3.9

# Copy application code
COPY src/ ./src/

# Create data directory
RUN mkdir -p /app/data

# Expose port
EXPOSE 8000

# Run the application
CMD ["uvicorn", "src.api.main:app", "--host", "0.0.0.0", "--port", "8000"]